﻿Imports System.ComponentModel
Imports PizzaManiaDAL

Public Class Form1

    Dim proxy As New PizzaService.Service1Client

    Dim Customers As New BindingList(Of Customer)
    Dim DeletedCustomers As New List(Of Customer)

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim customerList = proxy.GetAllCustomers()
        'Dim orderslist = proxy.GetOpenOrdersByCustomerID(1)

        For Each cust In customerList
            customers.Add(cust)
        Next

        Me.CustomerBindingSource.DataSource = customers
    End Sub


    Private Sub CustomerBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomerBindingNavigatorSaveItem.Click
        Me.CustomerBindingSource.EndEdit()

        'Me.Save()
        Me.SaveAll()
    End Sub

    ''' <summary>
    ''' Saves all in one database transaction 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SaveAll()

        Dim saved = False

        'Only save changes if there are some and they are valid

        If Not Me.HasChanges Then
            MsgBox("Please make changes before saving.")

        Else
            If Me.ValidateCustomers() Then

                Dim saveCusts = Me.Customers.ToArray()
                Dim delCusts = Me.DeletedCustomers.ToArray()

                Try
                    If saveCusts.Count > 0 OrElse delCusts.Count > 0 Then
                        'Update/insert orders/details
                        If proxy.SaveCustomers(saveCusts, delCusts) Then
                            Me.DeletedCustomers.Clear()
                            saved = True
                        End If
                    End If

                Catch ex As Exception
                    MsgBox(ex.ToString)
                End Try

                'Merges added keys and any validation errors
                Me.MergeCustomerList(saveCusts)

            End If

            If Me.HasErrors Then
                MsgBox("Please correct the errors on this form.")
            Else
                If saved Then
                    MsgBox("Your data was saved.")
                Else
                    MsgBox("Your data was not saved.")
                End If
            End If
        End If

    End Sub


    ''' <summary>
    ''' Save one by one
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Save()
        Try
            For Each c As Customer In Me.Customers
                If c.IsDirty Then
                    proxy.SaveCustomer(c, False)
                End If
            Next
            For Each c As Customer In Me.DeletedCustomers
                proxy.SaveCustomer(c, True)
            Next
            Me.DeletedCustomers.Clear()

            MsgBox("saved!")

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

   
    Private Sub BindingNavigatorDeleteItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorDeleteItem.Click
        If Me.CustomerBindingSource.Position > -1 Then
            Dim currentCust = CType(Me.CustomerBindingSource.Current, Customer)

            If currentCust IsNot Nothing AndAlso currentCust.Customer_ID > 0 Then
                deletedCustomers.Add(currentCust)
            End If
        End If
    End Sub

    ''' <summary>
    ''' Returns True if there are any validation errors on the business objects.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function HasErrors() As Boolean
        For Each c In Me.Customers
            If c.HasErrors Then Return True
        Next
        Return False
    End Function

    ''' <summary>
    ''' Validates all the customers
    ''' </summary>
    ''' <remarks></remarks>
    Private Function ValidateCustomers() As Boolean
        Try
            For Each c In Me.Customers
                c.Validate()
            Next
        Catch ex As ValidationException
            Return False
        End Try
        Return True
    End Function

    ''' <summary>
    ''' Returns True if there are any changes to any of the customers.
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function HasChanges() As Boolean
        If Me.DeletedCustomers.Count > 0 Then
            Return True
        End If
        For Each o In Me.Customers
            If o.IsDirty Then Return True
        Next
        Return False
    End Function

    ''' <summary>
    ''' Copies from array to the BindingList
    ''' </summary>
    ''' <param name="changes"></param>
    ''' <remarks></remarks>
    Private Sub MergeCustomerList(ByVal changes() As Customer)
        Dim pos = Me.CustomerBindingSource.Position
        Me.CustomerBindingSource.SuspendBinding()
        Me.CustomerBindingSource.RaiseListChangedEvents = False

        Me.Customers.Clear()
        For Each c In changes
            Me.Customers.Add(c)
        Next

        Me.CustomerBindingSource.ResumeBinding()
        Me.CustomerBindingSource.RaiseListChangedEvents = True
        Me.CustomerBindingSource.Position = pos
    End Sub

End Class
